//
//  BTBaseWebV.m
//  BaxTer
//
//  Created by wsj2015 on 2016/11/10.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTBaseWebVC.h"

@interface BTBaseWebVC ()

@property (nonatomic, strong) UIProgressView *progressView;

@property (nonatomic,  strong) NSURLRequest *request;


@end

@implementation BTBaseWebVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    [self.view addSubview:self.webView];
    [self wsj_showLodingGif];
    [self appendProgressView];
    
    weakSelf_define;
    [HELAppManager jSessionIdOverTime:^(NSString *sessionID) {
        NSMutableURLRequest *reques = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:weakSelf.url]];
        [reques  addValue:sessionID forHTTPHeaderField:@"x-auth-token"];
        WSJLog(@"%@",reques.allHTTPHeaderFields);
        weakSelf.webView.UIDelegate = self;
        [weakSelf.webView loadRequest:reques];
        
    } sessionFailure:^{
        
    }];

  
}

#pragma -mark 学习完成
- (void)uploadLearingProgress{
    
    
    NSMutableDictionary *params =[NSMutableDictionary
                                  dictionary];
    
    params[@"courseID"] =@([self.course.id integerValue]);
    [[BTNetworkManager sharedMg] POST:kUpdateLearningProgess parameters:params success:^(NSDictionary *responseObject) {
        
        if (responseObject[@"err"]&& ![responseObject[@"err"] isKindOfClass:[NSNull class]]) {
            alertMessage(responseObject[@"err"]);
        }else{
            
        }
        
    } failure:^(NSString *err) {
        
    }];
    
    
}

- (void)dealloc {

    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    self.webView.UIDelegate = nil;
    self.webView.navigationDelegate = nil;
    [self.webView removeFromSuperview];
    self.webView = nil;
}

#pragma mark - Getters
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0
- (WKWebView *)webView {
    if (_webView) return _webView;
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight- 64)];
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    return _webView;
}

#else
- (UIWebView *)webView {
    if (_webView) return _webView;
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight- 64)];
    _webView.delegate = self;
    _webView.scalesPageToFit = YES;
    _webView.translatesAutoresizingMaskIntoConstraints = NO;
    return _webView;
}
#endif
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0

- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    /*
     //navigationAction.request.URL
     WSJLog(@"正在加载%@",navigationAction.request.URL);
     WSJLog(@"%@",navigationAction.request.allHTTPHeaderFields);
     if (![[navigationAction.request.URL absoluteString] isEqualToString:@"https://www.baidu.com/"]) {
     decisionHandler(WKNavigationActionPolicyCancel);
     BTDetailConsultVC *detailVC = [[BTDetailConsultVC alloc] initWithUrl:[navigationAction.request.URL absoluteString]];
     detailVC.hidesBottomBarWhenPushed = YES;
     [self.navigationController pushViewController:detailVC animated:YES];
     
     }else {
     decisionHandler(WKNavigationActionPolicyAllow);
     }
     */
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    
    //    WSJLog(@"正在加载%@",navigationResponse.request.URL);
    decisionHandler(WKNavigationResponsePolicyAllow);
    
}

#pragma mark - WKNavigation delegate

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
   
    [self wsj_hideLodingGif];
    if (!self.navigationItem.title) {
        if ([self.tagKey isEqualToString:@"consult"]) {
            self.navigationItem.title = @"商业培训资讯站";
        }else{
           self.navigationItem.title = webView.title;
        }
       
    }
    
    
    //如果有课程传进来  完成进度上传 (考试是不传的,仅仅是微课)
    if (self.course) {
        if ([self.course.courseStatus integerValue] <2) {
            [self uploadLearingProgress];
        }
        
    }
    
   
}
 - (void)viewWillAppear:(BOOL)animated
{
    // 禁用 iOS7 返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    // 禁用 iOS7 返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self wsj_hideLodingGif];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

#else
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    webView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64);
    WSJLog(@"正在加载%@",request.URL);
    return YES;
}

#endif


#pragma mark - ProgressView
- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.trackTintColor = [UIColor whiteColor];
        _progressView.tintColor = kMainColor;
    }
    return _progressView;
}

- (void)appendProgressView {
    [self.view addSubview:self.progressView];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.hidden = self.webView.estimatedProgress == 1;
        float progress = self.progressView.hidden ? 0 : self.webView.estimatedProgress;
        [self.progressView setProgress:progress animated:YES];
    }
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.progressView.frame = CGRectMake(0, self.topLayoutGuide.length, self.view.frame.size.width, 0.5);
}



@end
